import { TOKEN, TOKEN_EXPIRATIONTIME } from '@/utils/storageTypes'
import { useClearUserInfo } from '@/hooks/user'
import store from '@/store'
import { SET_TGT_TOKEN, SET_TOKEN, SET_USER_INFO } from '@/store/types'
import current from '@/encrypt/current'
import { oauth2 } from '@/api/auth'

export function msg(content: any, mask= true, time = 3000) {
  return new Promise((resolve) => {
    uni.showToast({
      icon: 'none',
      title: content,
      duration: time,
      mask:mask,
      success() {
        resolve('success')
      },
    })
  })
}

export function showLoading(content = '加载数据中...', mask = true) {
  uni.showLoading({
    title: content,
    mask: mask,
  })
}

export function hideLoading(timer = 0) {
  if (timer > 0) {
    var t = setTimeout(function () {
      uni.hideLoading()
      clearTimeout(t)
    }, timer)
  } else {
    uni.hideLoading()
  }
  return Promise.resolve()
}

export function uuid(len: number = 16, radix: number = 16) {
  var chars =
    '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  var uuid = [],
    i
  radix = radix || chars.length

  if (len) {
    // Compact form
    for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)]
  } else {
    // rfc4122, version 4 form
    var r

    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
    uuid[14] = '4'

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16)
        uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r]
      }
    }
  }

  return uuid.join('')
}

export function showModal(options: UniApp.ShowModalOptions = {}) {
  return new Promise((resolve, reject) => {
    uni.showModal({
      title: '温馨提示',
      content: '该操作存在风险, 是否继续?',
      success: ({ cancel, confirm }) => {
        confirm && resolve(true)
        cancel && reject(false)
      },
      ...options,
    })
  })
}

export function isValidKey(key: string | number | symbol, object: object): key is keyof typeof object {
  return key in object;
}

export  const checkLogin = (noTig?:Boolean) => {
  const currentTime = new Date().getTime()
  const publicKeyExpireTime = uni.getStorageSync(TOKEN_EXPIRATIONTIME) || 0
  if (parseInt(publicKeyExpireTime) < currentTime) {
    // 登录时间过期,清空token
    // uni.removeStorageSync(TOKEN)
    const userKeys = [
      'userInfo',
      'threePartLoginData',
      'publicKeyExpireTime',
      'publicKey',
      'token',
      'token_expirationTime'
    ]
    userKeys.map((key) => uni.removeStorageSync(key))
    store.commit(`user/${SET_TGT_TOKEN}`, '')
    store.commit(`user/${SET_USER_INFO}`, '')
    store.commit(`user/${SET_TOKEN}`, '')
  }
  if(uni.getStorageSync(TOKEN)){
    // 登录进入
    return Promise.resolve()
  }else{
    if(!noTig){
      // #ifndef H5
      showModal({
        content:'您还未登陆，请登录后在进行操作！',
        confirmText:'前往登录',
        confirmColor:'#92C75B',
        cancelText:'再看看',
        cancelColor:'#929292'
      }).then(async res => {
        useClearUserInfo()
        uni.navigateTo({url:'/pageAuth/login/login'})
      })
      // #endif


      // #ifdef H5
      showModal({
        content:'登录已过期，请退出后重新进入',
        showCancel:true,confirmText:'退出',
        success:(res) =>{
          if(res.confirm){
            useClearUserInfo()
            window.location.replace('/#/')
          }
          if(res.cancel){
            useClearUserInfo()
          }
        }
      })
      // #endif
    }

    return Promise.reject()
  }
}

export const formValidate = (formData:any,rule:any) => {
  if(Array.isArray(formData)){
    for (let i = 0; i < formData.length; i++) {
       formValidate(formData[i],rule)
    }
  }else{
    const formDataKeys = Object.keys(formData)
    for(let i = 0; i< formDataKeys.length; i++){
      const key = formDataKeys[i]
      if(rule[key]){
        if(!formData[key].toString() || formData[key] == null){
          msg(rule[key].message,false)
          return Promise.reject(false)
        }else if (typeof formData[key] == 'object') {
          formValidate(formData[key],rule)
        }else {
          if( rule[key].patternType && rule[key].patternType == 'phone'){
           if(!phoneCode(formData[key])){
             msg('请输入正确的手机号',false)
             return Promise.reject(false)
           }
          }
          if(rule[key].patternType && rule[key].patternType == 'idCard'){
            if(!idCardCode(formData[key])){
              msg('请输入正确的身份证号',false)
              return Promise.reject(false)
            }
          }
          if(rule[key].pattern){
            if(!rule[key].pattern.test(formData[key])){
              msg(rule[key].patternMsg,false)
              return Promise.reject(false)
            }
          }
          if(rule[key].callback && typeof rule[key].callback == 'function'){
            rule[key].callback(formData[key],rule[key]).catch((err:any) => {
              msg(err.msg,false)
              return Promise.reject(false)
            })
          }
        }
      }else{

      }
    }
    return Promise.resolve(true)
  }
  return Promise.resolve(true)
}

export const phoneCode = (phone:string) => {
  if(!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(phone)){
    return false
  }
  return true
}
export const idCardCode = (idCard:string) => {
  if(!/^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(idCard)){
    return false
  }
  return true
}

// 格式化时间
export const formatDateTime = (date:any, format:string) => {
  const o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
    'H+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
    a: date.getHours() < 12 ? '上午' : '下午', // 上午/下午
    A: date.getHours() < 12 ? 'AM' : 'PM', // AM/PM
  };
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      );
    }
  }
  return format;
}

// 调用微信支付
export const wechatPayment = (data:any) => {
  return new Promise((resolve,reject) => {
    // #ifdef H5
    // H5 支付
    // #endif
    // #ifdef MP-WEIXIN
    // 微信小程序支付
    showLoading('正在支付...')
    uni.requestPayment({
      provider:'wxpay',
      ...data,
      success:(res:any) => {
        resolve(res)
      },
      fail:(err:any) => {
        reject(err)
      },
      complete:() => {
        hideLoading()
      }
    })
    // #endif
  })
}

// 图片预览
export const picturePreview = (current:string,urls:string[],showmenu:boolean = true) => {
  uni.previewImage({
    current,
    urls,
    showmenu,
    success:() => {
      return Promise.resolve()
    },
    fail:(err:UniApp.UniError) => {
      return Promise.reject(err)
    }
  })
}
